from models.database import DatabaseHelper
from models.device import DeviceRecord
from datetime import datetime
import logging


class DeviceService:
	def __init__(self):
		self.db = DatabaseHelper()
		self.logger = logging.getLogger("service")
	
	def create_record(self, record_data: dict):
		try:
			# 数据验证
			required_fields = ["machine_id", "owner_id", "record_type", "device_type"]
			for field in required_fields:
				if not record_data.get(field):
					raise ValueError(f"缺少必填字段: {field}")
			
			# 构建SQL
			fields = []
			values = []
			placeholders = []
			for field, value in record_data.items():
				fields.append(field)
				values.append(value)
				placeholders.append("?")
			
			sql = f"INSERT INTO {DeviceRecord.TABLE_NAME} ({', '.join(fields)}) VALUES ({', '.join(placeholders)})"
			self.db.execute(sql, tuple(values))
			self.logger.info(f"新建记录成功: {record_data}")
			return True
		except Exception as e:
			self.logger.error(f"创建记录失败: {str(e)}")
			raise
	
	def search_records(self, filters: dict, page: int = 1, page_size: int = 10):
		try:
			where_clauses = []
			params = []
			for key, value in filters.items():
				if value:
					where_clauses.append(f"{key} LIKE ?")
					params.append(f"%{value}%")
			
			base_sql = f"FROM {DeviceRecord.TABLE_NAME}"
			if where_clauses:
				base_sql += " WHERE " + " AND ".join(where_clauses)
			
			# 分页处理
			offset = (page - 1) * page_size
			sql = f"SELECT * {base_sql} LIMIT ? OFFSET ?"
			params.extend([page_size, offset])
			
			# 获取总数
			count_sql = f"SELECT COUNT(*) {base_sql}"
			total = self.db.fetch_all(count_sql, params[:-2])[0]["COUNT(*)"]
			
			records = self.db.fetch_all(sql, params)
			return {
				"data": records,
				"total": total,
				"page": page,
				"page_size": page_size
			}
		except Exception as e:
			self.logger.error(f"查询失败: {str(e)}")
			raise
